package com.FH.util;


import org.apache.commons.lang.xwork.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Title MD5.java
 * @Description MD5加密
 * @Copyright Copyright (c) 2014-7-3
 * @Company 陕通锦颐养老
 * @Author syf
 */
public class MD5 {
    /**
     * @Description 把传递过来的 String 字符串通过 MD5 算法加密，然后返回加密后生成的字符串
     * @Param  password 要加密的字段，这里指密码
     * @Return String 返回加密后的字符串
     * @Author syf 2012-8-31
     */
    public static String endcodPassword(String password) {
        String temp = "";
        try {
            //标准库中，只返回 byte[]
            MessageDigest md = MessageDigest.getInstance("MD5"); //定义MessageDigest对象
            md.update(password.getBytes("utf-8"));  //使用指定字节数组更新摘要
            //使用指定的字节数组对摘要进行最后更新，然后完成摘要计算
            byte[] byteTemp = md.digest(password.getBytes("utf-8"));

            //用非标准的库 sun.misc.* 进行 base64 转换
            BASE64Encoder b64encoder = new BASE64Encoder();
            temp = b64encoder.encode(byteTemp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace(); //打印错误信息;
            return null;
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
        return temp;
    }
    
    public static String md5(String plain)
  {
	String hs = "";
	String stmp = "";
	String temp = "";
	try {
		byte[] input = plain.getBytes();
	    MessageDigest alg = MessageDigest.getInstance("MD5");
		alg.update(input);
		byte[] encrypted = alg.digest();
		for (int n = 0; n < encrypted.length; n++) {
	        stmp = Integer.toHexString(encrypted[n] & 0xFF);
	        if (stmp.length() == 1)
	          hs = hs + "0" + stmp;
	        else {
	          hs = hs + stmp;
	        }

	      }
		BASE64Encoder b64encoder = new BASE64Encoder();
        temp = b64encoder.encode(encrypted);
		return temp;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(); //打印错误信息;
        return null;
    } 
  }
    
  public static String byte2hex(byte[] b)
  {
    String hs = "";
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
      stmp = Integer.toHexString(b[n] & 0xFF);
      if (stmp.length() == 1)
        hs = hs + "0" + stmp;
      else {
        hs = hs + stmp;
      }

    }

    return hs.toUpperCase();
  }
      
    
    /**
     * 获取访问者IP
     *
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     *
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip; 
            }
        } else {
            return request.getRemoteAddr();
        }
    }
    
    /**
     * 生成6位随机数
     * @param min
     * @param maxz
     * @return
     */
    public static int nextInt()
    {
    	Random random = new Random();
    	  return random.nextInt(899999)+100000;
    }
	/**
	 * MD5 32位加密
	 * @param sourceStr
	 * @return
	 */
    public static String MD5ThreeTwo(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
//            System.out.println("MD5(" + sourceStr + ",32) = " + result);
//            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }
}


